package com.base.control;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.cache.ACache;
import com.base.cache.AppConfigureControl;
import com.base.db.BaseDao;
import com.base.framework.R;
import com.base.model.Bean2Json;
import com.base.model.FindViewable;
import com.base.util.BackgroundSetter;
import com.base.util.ConstantResource;
import com.base.util.FileHelper;
import com.base.util.ImageUtil;
import com.base.util.MLog;
import com.base.util.UrlUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.Serializable;

//TODO 对activity栈的操作
public abstract class MActivitySupport extends ActionBarActivity implements AppConfigureControl, RequestCallback, FindViewable {
	protected View actionBarView;
    protected ACache aCache;
    protected DisplayMetrics metrics;
    private int layoutResID;

    protected static DisplayImageOptions.Builder builder; //单例
    protected static DisplayImageOptions.Builder builderWithLoading;

    protected View backBtn;
    protected TextView titleTv;
    private Button rightBtn;

    @Override
    public MActivitySupport getMActivity() {
        return this;
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        this.layoutResID = layoutResID;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //检查是否在此context是否有自定义的背景设置
        BackgroundSetter.checkAndSet(this, layoutResID);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BackgroundSetter.destroy(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    //set start bundle data
    public int getStartType() {
        int ret = 0;
        Intent intent = getIntent();
        if(intent != null) {
            ret = intent.getIntExtra(ConstantResource.START_TYPE, -1);
        }
        return ret;
    }

    public Bundle setStartType(int type) {
        Bundle data = new Bundle();
        data.putInt(ConstantResource.START_TYPE, type);
        return data;
    }

    public Serializable getStartData() {
        Serializable ret = null;
        Intent intent = getIntent();
        if(intent != null) {
            ret = intent.getSerializableExtra(ConstantResource.START_DATA);
        }
        return ret;
    }

    public Bundle setStartData(Serializable obj) {
        Bundle data = new Bundle();
        data.putSerializable(ConstantResource.START_DATA, obj);
        return data;
    }

    public Bundle setStartTypeAndData(int type, Serializable obj) {
        Bundle data = new Bundle();
        data.putInt(ConstantResource.START_TYPE, type);
        data.putSerializable(ConstantResource.START_DATA, obj);
        return data;
    }


    //操作Fragment
    public void replaceFragment(Fragment fragment, int layoutId, boolean addPopStack, Bundle data) {
        if(data != null) {
            fragment.setArguments(data);
        }
        FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
        transaction.replace(layoutId, fragment);
        if(addPopStack) {
            transaction.addToBackStack(null);
        }
        transaction.commit();
    }
	
	@SuppressWarnings("unchecked")
	protected <T> T mFindViewById(int id) {
		return (T)findViewById(id);
	}
    @Override
    public View findViewIdForSetBackground(int resid) {
        return findViewById(resid);
    }
    @Override
    public Context getContextForSetBackground() {
        return this;
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        ActivityStack.getScreenManager().pushActivity(this);
        ConstantResource.setImageLoader(this);
		create(savedInstanceState);
        setActionBar();
	}

    @Override
    public void finish() {
        ActivityStack.getScreenManager().popActivity(this);
        super.finish();
    }

    //清空activity栈
    public void clearActivity(Class<? extends Activity> claz) {
        ActivityStack.getScreenManager().popAllActivityExceptOne(claz);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ConstantResource.imageLoader.clearMemoryCache();
//        ConstantResource.imageLoader.clearDiskCache();
    }

    protected abstract void create(Bundle savedInstanceState);
	protected void setActionBar() {
		//do something in subClass
	}

    @Override
    final public ACache getACache() {
        if(aCache == null) {
            aCache = ACache.get(this);
        }
        return aCache;
    }

    //网络请求回调，子类可选实现
    @Override
    public void onRequestError(Integer errcode, String errmsg) {

    }

    @Override
    public void onRequestSuccess(Bean2Json data) {

    }


    //ImageLoader封装
    @Override
    public void setImageView(ImageView iv, int resid, ImageLoaderType type, boolean isfadein) {
        switch (type) {
            case DEFAULT:
                ConstantResource.imageLoader.displayImage(ImageUtil.DRAWABLE_PRE + resid, iv, getFadeinConfigImageLoader(isfadein));break;
        }

    }

    @Override
    public void setImageView(ImageView iv, int replaceId, ImageLoaderType type, boolean cleanCache, String imgId, int w, int h,
                             Integer loadingImg, boolean isRound, boolean isFadeIn, ImageLoadingListener imageLoadingListener) {
        String url;
        if(w == -1 && h == -1) {
            url = UrlUtils.getFileUrl(imgId);
        } else {
            url = UrlUtils.getFileUrl(imgId, w, h);
        }
        switch (type) {
            case DEFAULT:
                if(loadingImg != null) {
                    if(ConstantResource.hasImgCache(imgId, w, h))
                        loadingImg = null;
                }
                if(imageLoadingListener != null) {
                    ConstantResource.imageLoader.displayImage(url, iv, getWebImgLoader(replaceId, loadingImg, isRound, isFadeIn), imageLoadingListener);
                } else {
                    ConstantResource.imageLoader.displayImage(url, iv, getWebImgLoader(replaceId, loadingImg, isRound, isFadeIn));
                }

                break;
        }

    }

    /**
     *
     * @param iv
     * @param replaceId
     * @param filename
     * @param flag 1 从picture目录中获取， 2 从缩略图目录获取
     */
    public void setImageViewForFile(ImageView iv, int replaceId, String filename, int flag, ImageScaleType type) {
        ConstantResource.imageLoader.displayImage(FileHelper.fileUrlForImageLoader(filename, flag), iv, getImageLoader(false, false, null, replaceId,
                type, Bitmap.Config.RGB_565,
                null, true, null));
    }

    public void setImageViewForFile(ImageView iv, int replaceId, String filename, int flag, ImageScaleType type, boolean isRound, boolean fadeIn) {
        ConstantResource.imageLoader.displayImage(FileHelper.fileUrlForImageLoader(filename, flag), iv, getImageLoader(false, false, null, replaceId,
                type, Bitmap.Config.RGB_565,
                isRound ? new RoundedBitmapDisplayer(200) : null, fadeIn, null));
    }

    public void setImageViewWithRound(ImageView iv, int resid, boolean cleanCache, String imgId) {
        ConstantResource.imageLoader.displayImage(UrlUtils.getFileUrl(imgId), iv, getImageLoader(false, true, null, resid,
                ImageScaleType.IN_SAMPLE_INT, Bitmap.Config.RGB_565,
                new RoundedBitmapDisplayer(200), false, null));
    }

    public DisplayImageOptions getImageLoader(boolean cacheInMemory, boolean checkOnDisk,
                                      Integer drawableid, Integer replaceid, ImageScaleType type,
                                      Bitmap.Config bitMapconfig,
                                      BitmapDisplayer displayer, boolean fadein, Integer loadingImg) {
        if(builder == null) { //创建一次
            builder = new DisplayImageOptions.Builder();
        }
        if(builderWithLoading == null) {
            builderWithLoading = new DisplayImageOptions.Builder();
        }

        DisplayImageOptions.Builder builder1;
        if(loadingImg != null) {
            builder1 = builderWithLoading;
            builder1.showImageOnLoading(loadingImg);
        } else {
            builder1 = builder;
        }

        if(drawableid != null)
            builder1.showImageOnLoading(drawableid);
        if(displayer != null)
            builder1.displayer(displayer);
        else {
            builder1.displayer(new SimpleBitmapDisplayer());
        }

        if(fadein) {
            builder1.displayer(new FadeInBitmapDisplayer(1000)); //渐入动画
        }
        if(replaceid != null) {
            builder1.showImageOnFail(replaceid);
        } else {
            builder1.showImageOnFail(R.drawable.transparent);
        }

        DisplayImageOptions options = builder1 //create options
                .cacheInMemory(false)
                .cacheOnDisk(true)
                .imageScaleType(type)
                .bitmapConfig(bitMapconfig)
                .build();

        return options;
    }

    public static enum ImageLoaderType {
        DEFAULT
    }

    public DisplayImageOptions getDefualtConfigImageLoader() {
        return getImageLoader(false, true, null, null, ImageScaleType.IN_SAMPLE_INT, Bitmap.Config.RGB_565, null, false, null);
    }

    public DisplayImageOptions getFadeinConfigImageLoader(boolean isfadein) {
        return getImageLoader(false, true, null, null, ImageScaleType.IN_SAMPLE_INT, Bitmap.Config.RGB_565, null, isfadein, null);
    }

    public DisplayImageOptions getWebImgLoader(int replaceId, Integer loadingImg, boolean isRound, boolean isFadeIn) {
        return getImageLoader(false, true, null, replaceId, ImageScaleType.IN_SAMPLE_INT, Bitmap.Config.RGB_565, isRound ? new RoundedBitmapDisplayer(200) : null, isFadeIn, loadingImg);
    }

    public ViewGroup getContentView(){
        ViewGroup systemContent = (ViewGroup)this.getWindow().getDecorView().findViewById(android.R.id.content);
        ViewGroup content = null;
        if(systemContent.getChildCount() > 0 && systemContent.getChildAt(0) instanceof ViewGroup){
            content = (ViewGroup)systemContent.getChildAt(0);
        }
        return content;
    }

    //设置字体
    public void changeFonts(ViewGroup root, Activity act) {

        Typeface tf = Typeface.createFromAsset(act.getAssets(),
                "fonts/fangzhenglanting.ttf");

        for (int i = 0; i < root.getChildCount(); i++) {
            View v = root.getChildAt(i);
            if (v instanceof TextView) {
                ((TextView) v).setTypeface(tf);
            } else if (v instanceof Button) {
                ((Button) v).setTypeface(tf);
            } else if (v instanceof EditText) {
                ((EditText) v).setTypeface(tf);
            } else if (v instanceof ViewGroup) {
                changeFonts((ViewGroup) v, act);
            }
        }

    }

    @Override
    public BaseDao getBaseDao() {
        throw new UnsupportedOperationException("请在MDaoActivity中使用该方法");
    }

    //手机状态获取
    //获取屏幕尺寸
    public DisplayMetrics getMetrics() {
        if(metrics == null) {
            metrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metrics);
        }
        return metrics;
    }

    /**
     * 是否开启了重力感应
     * @return
     */
    public boolean screenIsOpenRotate() {
        int gravity = 0;
        try {
            gravity = Settings.System.getInt(this.getContentResolver(),
                    Settings.System.ACCELEROMETER_ROTATION);
        } catch (Settings.SettingNotFoundException e) {
            MLog.e(e);
        }
        if (gravity == 1) {
            return true;
        }
        return false;
    }

    //禁用菜单键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            // do nothing
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public View getBackBtn() {
        return backBtn;
    }

    public void setBackBtn(View backBtn) {
        this.backBtn = backBtn;
    }

    public TextView getTitleTv() {
        return titleTv;
    }

    public void setTitleTv(TextView titleTv) {
        this.titleTv = titleTv;
    }

    public Button getRightBtn() {
        return rightBtn;
    }

    public void setRightBtn(Button rightBtn) {
        this.rightBtn = rightBtn;
    }
}
